/**
 * @file     minSwaps.ts
 * @brief    [2134. 最少交换次数来组合所有的 1 II](https://leetcode.cn/problems/minimum-swaps-to-group-all-1s-together-ii/description/)
 * @author   Zhu
 * @date     2024-11-21 21:52
 */

function minSwaps(nums: number[]): number {
    const n = nums.length;
    let k = 0;
    for (let i = 0; i < n; i++) {
        if (nums[i] === 1) {
            k++;
        }
    }

    const get = (i: number) => nums[i % n];
    let i = 0,
        ones = 0,
        max = 0;
    while (i < k + n) {
        ones += get(i) - (i < k ? 0 : get(i - k));
        if (ones > max) max = ones;
        i++;
    }

    return k - max;
}
